/*
 * $Id: OpenForEditAction.java 23 2002-09-29 13:59:30Z bpruessmann $
 * 
 * Copyright (c) 2001,2002 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.p4eclipse.ui.action;

import java.lang.reflect.InvocationTargetException;

import net.sourceforge.p4eclipse.core.PerforceRepositoryProvider;
import net.sourceforge.p4eclipse.ui.PerforceUIPlugin;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ui.actions.TeamAction;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.actions.WorkspaceModifyOperation;

/**
  * @version 	$Revision: 23 $
  * @author		<a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
public class OpenForEditAction extends TeamAction                                
{
	/*
	 * @see TeamAction#isEnabled()
	 */
	protected boolean isEnabled() 
		throws TeamException
	{
		if (PerforceUIPlugin.getClient().dropped())
			return false;		
		
		IResource[] resources = getSelectedResources();
		if (resources.length == 0) 
			return false;
			
		for (int i = 0; i < resources.length; i++) 
		{
			RepositoryProvider tempProvider = RepositoryProvider.getProvider(resources[i].getProject());
			if (tempProvider == null || !tempProvider.getID().equals(PerforceUIPlugin.getTypeId()))
				return false;
				
			PerforceRepositoryProvider provider = (PerforceRepositoryProvider)tempProvider;
			if (!provider.hasRemote(resources[i]))
				return false;
				
			if (provider.isCheckedOut(resources[i])) 
				return false;
		}
		return true;
	}
	
	/* @see org.eclipse.team.internal.ui.actions.TeamAction#getSelectedResources() */
	protected IResource[] getSelectedResources()
	{
		return super.getSelectedResources();
	}
	
	/*
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action)
	{		
		run(
			new WorkspaceModifyOperation()
			{
				public void execute(IProgressMonitor monitor) 
					throws InterruptedException, InvocationTargetException 
				{
					IResource[] resources = getSelectedResources();
					try
					{
						PerforceRepositoryProvider provider = (PerforceRepositoryProvider)RepositoryProvider.getProvider(resources[0].getProject());						
						provider.checkout(resources, IResource.DEPTH_INFINITE, monitor);
					}
					catch (TeamException e)
					{
						throw new InvocationTargetException(e);
					}					
				}				
			}, "OpenForEditAction failed.", PROGRESS_DIALOG);
	}
}
